﻿using Aspose.Cells;
using System;
using System.IO;
using System.Windows.Forms;

namespace TeacherHelp.FormList.Teacher
{
    public partial class ImportExercisesForm : BanFlashingForm
    {
        public ImportExercisesForm()
        {
            InitializeComponent();
        }

        private void SelectFileBtn_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog fileDialog = new OpenFileDialog())
            {
                fileDialog.Filter = "(*.xls)|*.xls|(*.xlsx)|*.xlsx";
                if (fileDialog.ShowDialog() == DialogResult.OK)
                {
                    FilePathTxt.Text = fileDialog.FileName;
                }
            }
        }

        private void FilePathTxt_TextChanged(object sender, EventArgs e)
        {
            string path = this.FilePathTxt.Text;
            if (File.Exists(path) && (Path.GetExtension(path) == ".xls" || Path.GetExtension(path) == ".xlsx"))
            {
                this.ImportBtn.Visible = true;
            }
            else
            {
                this.ImportBtn.Visible = false;
            }
        }

        private void downloadTemplateLable_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            using (SaveFileDialog fileDialog = new SaveFileDialog())
            {
                fileDialog.Title = "另存为";
                fileDialog.Filter = "(*.xlsx)|*.xlsx|(*.xls)|*.xls";
                fileDialog.DefaultExt = "xlsx";
                fileDialog.FileName = "题目模板.xlsx";
                if (fileDialog.ShowDialog() == DialogResult.OK)
                {
                    if (!File.Exists("Tempalate\\题目模板.xlsx"))
                    {
                        MessageBox.Show("题目模板文件丢失！！！", "异常提示", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                        return;
                    }
                    //存在就删除，进行覆盖
                    if (File.Exists(fileDialog.FileName))
                        File.Delete(fileDialog.FileName);

                    File.Move("Tempalate\\题目模板.xlsx", fileDialog.FileName);
                    MessageBox.Show("下载成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }

            }
        }

        private void ImportBtn_Click(object sender, EventArgs e)
        {
            string path = this.FilePathTxt.Text;
            var table = new Util.ExeclTool(path).getFirstDataTable();
            BLL.ImportSubjectManager importSubjectManager = new BLL.ImportSubjectManager();
            this.ExercisesInfoGridView.DataSource = table;
            string result = importSubjectManager.ImportDataTable(table);

            if (string.IsNullOrEmpty(result))
            {
                MessageBox.Show("导入成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show(result, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}
